<!-- 消息 -->
<template>
  <div class="box">
    <div class="top">
      <div class="top_one">
        <div class="title">
          消息
        </div>
        <div class="right">
          <svgIcon iconName="icon-qunliao1" font-size="38px"></svgIcon>
          发现群聊
        </div>
      </div>
      <div class="top_two">
        <div class="love" @click="$router.push('/newszan')">
          <span>
            <svgIcon iconName="icon-xz" font-size="60px"></svgIcon>
          </span>
          <p>赞和收藏</p>
        </div>
        <div class="my_user" @click="$router.push('/newsfollow')">
          <span style="background-color: #e6effe;">
            <svgIcon iconName="icon-fensi" font-size="60px"></svgIcon>
          </span>
          <p>新增关注</p>
        </div>
        <div class="comment" @click="$router.push('/newscomment')">
          <span style="background-color: #e7fbf2;">
            <svgIcon iconName="icon-xinxi" font-size="60px"></svgIcon>
          </span>
          <p>评论和@</p>
        </div>
      </div>
    </div>
    <div class="content">
      <!-- 系统消息 -->
      <!-- <div class="item" @click="router.push('/information')">
        <div class="pic"></div>
        <div class="nr">
          <div class="nr_title">
            系统消息
          </div>
          <div class="nr_text">
            您的优惠卷将要过期啦！
          </div>
        </div>
        <div class="time">
          2023-02-19
        </div>
      </div> -->
      
      <!-- 聊天列表 -->
      <div 
        v-for="chat in chatList" 
        :key="chat.userId" 
        class="item" 
        @click="handleChatClick(chat)"
      >
        <div class="pic">
          <img 
            v-if="chat.avatar_url" 
            :src="chat.avatar_url" 
            alt="用户头像"
          >
          <img 
            v-else 
            :src="defaultAvatar" 
            alt="默认头像"
          >
        </div>
        <div class="nr">
          <div class="nr_title">
            {{ chat.nickname || '未设置昵称' }}
            <span v-if="chat.unreadCount > 0" class="unread-badge">{{ chat.unreadCount/2 }}</span>
          </div>
          <div class="nr_text">
            {{ chat.lastMessage || '暂无消息' }}
          </div>
        </div>
        <div class="time">
          {{ formatTime(chat.lastMessageTime) }}
        </div>
      </div>
      
      <!-- 无聊天记录时的提示 -->
      <div v-if="chatList.length === 0" class="empty-tip">
        <div class="empty-text">暂无聊天记录</div>
      </div>
    </div>
    <NavFooter />
  </div>
</template>

<script setup>
import NavFooter from '@/components/NavFooter.vue'
import svgIcon from '@/components/svgIcon.vue';
import router from '@/router';
import { ref, onMounted, onUnmounted } from 'vue';
import axios from 'axios';
import defaultAvatar from '@/assets/czq/pic.png';
import { showToast } from 'vant';
import websocketService from '@/services/websocket';

// 聊天列表
const chatList = ref([]);

// 获取聊天列表
const fetchChatList = async () => {
  try {
    const currentUserId = localStorage.getItem('user_id');
    if (!currentUserId) {
      showToast('请先登录');
      return;
    }

    // 从本地存储获取聊天记录
    const chatRecords = JSON.parse(localStorage.getItem('chatRecords') || '{}');
    
    // 筛选出当前用户的聊天记录
    const userChats = [];
    Object.keys(chatRecords).forEach(key => {
      if (key.startsWith(`${currentUserId}_`)) {
        const chat = chatRecords[key];
        userChats.push({
          userId: chat.userId,
          nickname: chat.nickname,
          avatar_url: chat.avatar_url,
          lastMessage: chat.lastMessage,
          lastMessageTime: new Date(chat.lastMessageTime),
          unreadCount: chat.unreadCount || 0
        });
      }
    });

    // 按最后消息时间排序（最新的在前面）
    userChats.sort((a, b) => b.lastMessageTime - a.lastMessageTime);

    // 获取每个聊天用户的详细信息（如果本地存储的信息不完整）
    const chatListWithDetails = await Promise.all(
      userChats.map(async (chat) => {
        try {
          // 如果本地存储的用户信息不完整，则从API获取
          if (!chat.nickname || !chat.avatar_url) {
            const response = await axios.get(`http://1.14.98.17:8765/api/users/${chat.userId}`);
            if (response.data.success) {
              return {
                ...chat,
                nickname: response.data.data.nickname || chat.nickname,
                avatar_url: response.data.data.avatar_url || ''
              };
            }
          }
          return chat;
        } catch (error) {
          console.error(`获取用户 ${chat.userId} 信息失败:`, error);
          return chat;
        }
      })
    );

    chatList.value = chatListWithDetails;
  } catch (error) {
    console.error('获取聊天列表失败:', error);
    showToast('获取聊天列表失败');
  }
};

// 处理聊天项点击
const handleChatClick = (chat) => {
  // 清除未读消息数
  clearUnreadCount(chat.userId);
  
  // 跳转到私信页面
  router.push({
    path: '/information',
    query: {
      userId: chat.userId
    }
  });
};

// 清除未读消息数
const clearUnreadCount = (targetUserId) => {
  try {
    const currentUserId = localStorage.getItem('user_id');
    if (!currentUserId) return;

    const chatRecords = JSON.parse(localStorage.getItem('chatRecords') || '{}');
    const chatKey = `${currentUserId}_${targetUserId}`;
    
    if (chatRecords[chatKey]) {
      chatRecords[chatKey].unreadCount = 0;
      localStorage.setItem('chatRecords', JSON.stringify(chatRecords));
    }
  } catch (error) {
    console.error('清除未读消息数失败:', error);
  }
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  
  const now = new Date();
  const time = new Date(timestamp);
  
  if (isNaN(time.getTime())) {
    return '';
  }
  
  const diff = now - time;
  
  // 十分钟内
  if (diff < 10 * 60 * 1000) {
    return '刚刚';
  }
  
  // 24小时内
  if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000));
    const minutes = Math.floor(diff / (60 * 1000));
    
    if (hours === 0) {
      return `${minutes}分钟前`;
    } else {
      return `${hours}小时前`;
    }
  }
  
  // 本年内
  if (time.getFullYear() === now.getFullYear()) {
    const month = String(time.getMonth() + 1).padStart(2, '0');
    const day = String(time.getDate()).padStart(2, '0');
    return `${month}-${day}`;
  }
  
  // 超过本年
  const year = time.getFullYear();
  const month = String(time.getMonth() + 1).padStart(2, '0');
  const day = String(time.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 处理新消息
const handleNewMessage = ({ from, message }) => {
  console.log('News.vue 收到新消息，开始处理:', { from, message });
  
  // 立即更新聊天列表，而不是重新获取
  updateChatListWithNewMessage(from, message);
};

// 更新聊天列表（添加新消息）
const updateChatListWithNewMessage = async (from, message) => {
  try {
    console.log('开始更新聊天列表:', { from, message });
    
    const currentUserId = localStorage.getItem('user_id');
    if (!currentUserId) {
      console.log('当前用户未登录，跳过更新');
      return;
    }

    // 从本地存储获取最新的聊天记录
    const chatRecords = JSON.parse(localStorage.getItem('chatRecords') || '{}');
    console.log('从本地存储获取的聊天记录:', chatRecords);
    
    const chatKey = `${currentUserId}_${from}`;
    const chatRecord = chatRecords[chatKey];
    console.log('聊天记录key:', chatKey, '现有记录:', chatRecord);

    if (chatRecord) {
      console.log('更新现有聊天记录');
      // 更新现有聊天记录
      chatRecord.lastMessage = message;
      chatRecord.lastMessageTime = new Date().toISOString();
      chatRecord.unreadCount = (chatRecord.unreadCount || 0) + 1;
    } else {
      console.log('创建新的聊天记录');
      // 创建新的聊天记录
      let userInfo = {
        nickname: '未知用户',
        avatar_url: ''
      };

      // 尝试获取用户信息
      try {
        console.log('尝试获取用户信息:', from);
        const response = await axios.get(`http://1.14.98.17:8765/api/users/${from}`);
        if (response.data.success) {
          userInfo = {
            nickname: response.data.data.nickname || '未知用户',
            avatar_url: response.data.data.avatar_url || ''
          };
          console.log('获取到用户信息:', userInfo);
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }

      chatRecords[chatKey] = {
        userId: from,
        nickname: userInfo.nickname,
        avatar_url: userInfo.avatar_url,
        lastMessage: message,
        lastMessageTime: new Date().toISOString(),
        unreadCount: 1
      };
    }

    // 保存到本地存储
    localStorage.setItem('chatRecords', JSON.stringify(chatRecords));
    console.log('保存到本地存储完成');

    // 重新构建聊天列表
    const userChats = [];
    Object.keys(chatRecords).forEach(key => {
      if (key.startsWith(`${currentUserId}_`)) {
        const chat = chatRecords[key];
        userChats.push({
          userId: chat.userId,
          nickname: chat.nickname,
          avatar_url: chat.avatar_url,
          lastMessage: chat.lastMessage,
          lastMessageTime: new Date(chat.lastMessageTime),
          unreadCount: chat.unreadCount || 0
        });
      }
    });

    console.log('构建的聊天列表:', userChats);

    // 按最后消息时间排序（最新的在前面）
    userChats.sort((a, b) => b.lastMessageTime - a.lastMessageTime);
    console.log('排序后的聊天列表:', userChats);

    // 更新聊天列表
    chatList.value = userChats;

    console.log('聊天列表更新完成，当前列表长度:', chatList.value.length);
  } catch (error) {
    console.error('更新聊天列表失败:', error);
  }
};

onMounted(() => {
  console.log('News.vue 组件挂载，开始初始化');
  console.log('WebSocket 连接状态:', websocketService.getConnectionStatus());
  
  fetchChatList();
  
  // 注册消息处理器
  websocketService.addMessageHandler(handleNewMessage);
  console.log('News.vue 消息处理器注册完成');
  console.log('注册后的 WebSocket 连接状态:', websocketService.getConnectionStatus());
});

onUnmounted(() => {
  console.log('News.vue 组件卸载，移除消息处理器');
  // 移除消息处理器
  websocketService.removeMessageHandler(handleNewMessage);
});
</script>
<style lang="less" scoped>
  .box {
    width: 100%;
    height: 100vh;
    background-color: #fff;
    .top {
      width: 100%;
      height: 300px;
      font-size: 32px;
      position: fixed;
      background-color: #fff;
      top: 0;
      left: 0;
      z-index: 10;
      .top_one {
        width: 100%;
        height: 100px;
        display: flex;
        justify-content: space-between;
        .title {
          margin-left: 345px;
          height: 100px;
          text-align: center;
          line-height: 100px;
        }
        .right {
          height: 100px;
          width: 220px;
          text-align: center;
          line-height: 100px;
          text-align: center;
          line-height: 100px;
        }
      }
      .top_two {
        width: 100%;
        height: 200px;
        display: flex;
        justify-content: space-around;
        align-items: center;
        div {
          width: 130px;
          height: 100%;
          span {
            display: block;
            padding: 17px;
            margin: 0 auto;
            margin-top: 35px;
            width: 90px;
            height: 90px;
            border-radius: 30px;
            background-color: #fce2e1;
          }
          p {
            margin-top: 20px;
          }
        }
      }
    }
    .content {
      margin-top: 300px;
      width: 100%;
      .item {
        width: 100%;
        height: 150px;
        padding: 0 30px;
        display: flex;
        align-items: center;
        border-bottom: 1px solid #eee;
        cursor: pointer;
        transition: background-color 0.2s;
        
        &:hover {
          background-color: #f5f5f5;
        }
        
        .pic {
          width: 90px;
          height: 90px;
          background-image: url('@/assets/czq/pic.png');
          background-size: 100% 100%;
          background-repeat: no-repeat;
          border-radius: 50%;
          overflow: hidden;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 50%;
          }
        }
        .nr {
          margin-left: 20px;
          width: 430px;
          height: 80px;
          .nr_title {
            font-size: 32px;
            font-weight: 500;
            margin-bottom: 8px;
            position: relative;
            
            .unread-badge {
              position: absolute;
              top: -8px;
              right: -20px;
              background-color: #ff4757;
              color: #fff;
              font-size: 20px;
              padding: 2px 8px;
              border-radius: 10px;
              min-width: 20px;
              text-align: center;
              line-height: 1.2;
            }
          }
          .nr_text {
            font-size: 28px;
            color: #989898;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
        .time {
          margin-left: 15px;
          height: 80px;
          font-size: 26px;
          color: #989898;
          display: flex;
          align-items: center;
        }
      }
      
      .empty-tip {
        width: 100%;
        height: 200px;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .empty-text {
          font-size: 28px;
          color: #999;
        }
      }
    }
  }
</style>
